package zhengqc.union_find;

public class UnionFindUsingQuickUnionRank implements UnionFind {
    private int[] parents;
    private int[] rank;  // rank[i] 表示根节点为 i 的树的高度

    public UnionFindUsingQuickUnionRank(int size) {
        this.parents = new int[size];
        this.rank = new int[size];
        for (int i = 0; i < size; ++i) {
            parents[i] = i;
            rank[i] = 1;
        }
    }
    private void rangeCheck(int index) {
        if (index < 0 || index >= parents.length) {
            throw new IllegalArgumentException(index + " is out of bound!");
        }
    }
    private int find(int p) {
        rangeCheck(p);
        while (p != parents[p]) {
            p = parents[p];
        }
        return p;
    }
    @Override
    public int getSize() {
        return parents.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElement(int p, int q) {
        int pRoot = find(p),
            qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }
        // 根据两个元素所在树的 rank 不同来判断合并方向
        // 将 rank 低的集合合并到 rank 高的集合上
        if (rank[pRoot] < rank[qRoot]) {
            parents[pRoot] = qRoot;
        } else if (rank[qRoot] < rank[pRoot]) {
            parents[qRoot] = pRoot;
        } else { // rank[qRoot] == rank[pRoot]
            parents[qRoot] = pRoot;
            rank[pRoot] += 1;
        }

    }
}
